﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RPSImporter.Properties;
using RPSImporter.Models;
using System.Reflection;
using RPSImporter.Infrastructure.Attributes;
using System.Resources;

namespace RPSImporter.Infrastructure
{
   public enum FileType
   {
      XLS,
      XML,
      CSV,
   }

   public class Util
   {
      public static IEnumerable<string> SupportedFiles
      {
         get
         {
            yield return GetFileTypeName<Person>(); //Resources.Persons_FileType;
            yield return GetFileTypeName<Company>(); //Resources.Companies_FileType;
            yield return GetFileTypeName<Enterprise>(); //Resources.Enterprises_FileType;
            yield return GetFileTypeName<EnterpriseExt>(); //Resources.EnterpriseExtern_FileType;
            yield return GetFileTypeName<Hierarchy>(); //Resources.Hierarchy_FileType;
            yield return GetFileTypeName<HoursPerson>(); //Resources.PersonHours_FileType;
            yield return GetFileTypeName<HoursHierarchy>(); //Resources.HierarchyHours_FileType;
         }
      }

      public static string GetFileTypeName<T>() where T: IModel
      {
         MemberInfo model = typeof(T);
         FileTypeNameAttribute fileType = (FileTypeNameAttribute)model.
                                                GetCustomAttributes(typeof(FileTypeNameAttribute), false).FirstOrDefault();
         if (fileType != null)
         {
            ResourceManager manager = new ResourceManager(typeof(Resources));
            return manager.GetString(fileType.Name);
         }
         return null;
      }

      public static Type GetFileType(string fileType)
      {
         var type = typeof(IModel);
         var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                               .SelectMany(s => s.GetTypes())
                               .Where(p => type.IsAssignableFrom(p));

         Type model = null;
         foreach (var item in types)
         {
            FileTypeNameAttribute attr = (FileTypeNameAttribute)item.GetCustomAttributes(typeof(FileTypeNameAttribute), false).FirstOrDefault();
            if (attr == null) continue;

            ResourceManager mgr = new ResourceManager(typeof(Resources));
            if (mgr.GetString(attr.Name) == fileType)
            {
               model = item;
               break;
            }
         }
         return model;
      }

      public class Result
      {
         public Result()
         {
            this.Messages = new List<string>();
         }
         public IList<string> Messages { get; set; }
      }
   }
}